<template>
  <div class="add-goods">
    <!-- 顶部步骤栏 -->
    <div class="top-nav">
      <!-- 步骤栏 -->
      <el-alert :title="msgtitle + '商品信息'" type="info" show-icon :closable="false" :center="true" />
      <el-steps :active="Number(active)" finish-status="success" align-center>
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品内容" />
        <el-step title="完成" />
      </el-steps>
    </div>
    <!-- 中间标签页 -->
    <div class="main-nav">
      <el-tabs tab-position="left" class="demo-tabs" v-model="active" :before-leave="beforLevel" v-show="active != 6">
        <el-tab-pane label="基本信息" :name="0">
          <add-base></add-base>
          <el-button type="primary" @click="active = 1"> 下一页 </el-button>
        </el-tab-pane>

        <el-tab-pane label="商品参数" :name="1">
          <!-- 防止未加载时访问 -->
          <template v-if="active == 1">
            <div v-for="(item, index) in form1.attrs" :key="item.id">
              <template v-if="
                item.attr_sel == 'many' && item.attr_value instanceof Array
              ">
                <span>{{ item.attr_name }}</span>
                <p>
                  <el-checkbox-group v-model="item.attr_value" size="large">
                    <el-checkbox v-for="item2 in form1.attrs[index].attr_vals" :key="item2" :label="item2" border />
                  </el-checkbox-group>
                </p>
              </template>
            </div>
          </template>

          <el-button type="primary" @click="active = 2">下一页</el-button>
        </el-tab-pane>

        <el-tab-pane label="商品属性" :name="2">
          <template v-if="active == 2">
            <goods-attr-com></goods-attr-com>
          </template>

          <el-button type="primary" @click="active = 3"> 下一页 </el-button>
        </el-tab-pane>
        <el-tab-pane label="商品图片" :name="3">
          <template v-if="active == 3">
            <upload-img></upload-img>
          </template>

          <el-button type="primary" @click="active = 4"> 下一页 </el-button>
        </el-tab-pane>
        <el-tab-pane label="商品内容" :name="4">
          <template v-if="active == 4">
            <content-goods></content-goods>
          </template>

          <el-button type="primary" @click="onsubmit(5)"> 提交 </el-button>
        </el-tab-pane>
      </el-tabs>
      <div v-if="active == 6" class="finish">
        <p class="icon-p">
          <el-icon :color="iconColor" size="30px">
            <CircleCheckFilled v-if="iconType" />
            <CircleCloseFilled v-else />
          </el-icon>
          <span>{{ msg }}</span>
        </p>

        <p>
          <img src="@/assets/images/wait.gif" alt="" />
        </p>
        <p>
          <el-button type="success" @click="backPage()">
            {{ `点击返回上一页 (${timeout}秒后自动跳转)` }}</el-button>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { provide, reactive, ref } from "vue";
// import { useStore } from "vuex";
import AddBase from "../../components/commdity/AddBase.vue";
import { ElMessage } from "element-plus";
import { getAttrs, getIdGoods, setGoods } from "@/api/goods";
import GoodsAttrCom from "../../components/commdity/GoodsAttrCom.vue";
import ContentGoods from "../../components/commdity/ContentGoods.vue";
import UploadImg from "../../components/commdity/UploadImg.vue";
import { useRouter } from "vue-router";
import { addGoods } from "@/api/goods";
import { useStore } from "vuex";

// *************  数据
let active = ref(0);
// let store = useStore();
let form1 = reactive({});
form1.attrs = reactive([]);
let store = useStore();
let msgtitle = ref("创建");
let oldId = -1;
let msg = ref("错误");
if (store.state.goodsFormType.type == 2) {
  msgtitle.value = "修改";
  (async () => {
    let res = await getIdGoods(store.state.goodsFormType.id);
    Object.assign(form1, res.data);
  })();
}

let timeout = ref(5);
let iconType = ref(true);
let iconColor = ref("#67c23a");

let timeset;
provide("form1", form1);
let router = useRouter();
//*************   函数
const changeattrs = async (id) => {
  if (store.state.goodsFormType.type == 1) {
    form1.attrs.splice(0);
  }

  //创建参数选项基础信息

  //获取many列表
  let res = await getAttrs(id, { sel: "many" });
  for (let i = 0; i < res.data.length; i++) {
    if (store.state.goodsFormType.type == 1) {
      form1.attrs.push(JSON.parse(JSON.stringify(res.data[i])));
    }
  }
  //获取only列表
  let res2 = await getAttrs(id, { sel: "only" });
  res2.data.forEach((element) => {
    if (store.state.goodsFormType.type == 1) {
      form1.attrs.push(JSON.parse(JSON.stringify(element))); //深拷贝
    }
  });

  for (let i = 0; i < form1.attrs.length; i++) {
    if (store.state.goodsFormType.type == 1) {
      form1.attrs[i].attr_value = form1.attrs[i].attr_vals;
      if (form1.attrs[i].attr_sel == "many") {
        form1.attrs[i].attr_vals = form1.attrs[i].attr_vals.split(",");
        form1.attrs[i].attr_value = reactive([]);
      }
    } else {
      if (form1.attrs[i].attr_sel == "many") {
        form1.attrs[i].attr_vals = form1.attrs[i].attr_vals.split(",");
        form1.attrs[i].attr_value = form1.attrs[i].attr_value.split(",");
      }
    }
  }

  let array = sortAttrs(form1.attrs);
  form1.attrs.splice(0);
  form1.attrs.push(...array);
  //排序

  //清空
};
const sortAttrs = (array) => {
  for (let i = 0; i < form1.attrs.length; i++) {
    for (let j = i + 1; j < form1.attrs.length; j++) {
      if (array[i].attr_id > array[j].attr_id) {
        [array[i], array[j]] = [array[j], array[i]];
      }
    }
  }
  return JSON.parse(JSON.stringify(array));
};
const beforLevel = (activeName, oldActiveName) => {
  if (oldActiveName == 0) {
    //修改
    if (store.state.goodsFormType.type == 2) {
      let ls = form1.goods_cat.split(",");
      let id = ls[ls.length - 1];
      if (oldId != id) changeattrs(id);
      oldId = id;
      return true;
    }
    //新增
    else {
      if (form1.goods_cat && form1.goods_cat.length == 0) {
        ElMessage.error("请选择商品分类");
        return false;
      } else {
        let ls = form1.goods_cat.length;
        let id = form1.goods_cat[ls - 1];
        changeattrs(id);
      }
      return true;
    }
  }
  return true;
};
//提交
const onsubmit = async () => {
  form1.attrs.forEach((element) => {
    if (element.attr_sel == "many") {
      element.attr_vals = String(element.attr_vals);
      element.attr_value = String(element.attr_value);
    }
  });
  let res;
  //创建请求
  if (store.state.goodsFormType.type == 1) {
    form1.goods_cat = String(form1.goods_cat);
    res = await addGoods(form1);
  }
  //修改请求
  else {
    res = await setGoods(store.state.goodsFormType.id, form1);
  }
  //处理提交返回的数据
  msg.value = res.meta.msg;
  let ls = res.meta.status >= 200 && res.meta.status < 300;
  if (!ls) {
    iconColor.value = "#f56c6c";
    iconType.value = false;
  }
  timeset = setInterval(() => {
    timeout.value--;
    if (timeout.value <= 0) {
      backPage();
    }
  }, 1000);
  active.value = 6;
};
//返回上一页
const backPage = () => {
  if (timeset) clearInterval(timeset);
  router.back();
};
</script>

<style lang="scss" scoped>
.add-goods {
  position: relative;
  width: 100%;
  background-color: white;

  .top-nav {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;

    .el-alert {
      margin: 0 auto 10px auto;
      width: 90%;
    }
  }

  .main-nav {
    width: 100%;
    padding: 0 20px 20px 20px;
    box-sizing: border-box;

    .el-tabs {
      overflow: visible;
    }

    .el-button {
      margin-top: 10px;
    }
  }
}

.finish {
  text-align: center;
  margin: auto;

  .icon-p {
    display: flex;
    align-items: center;
    height: 40px;
    line-height: 40px;
    justify-content: center;
  }
}
</style>